/*
 * @Author: 白川 杏 baiyufeisteam@163.com
 * @Date: 2023-03-10 08:57:41
 * @LastEditors: 白川 杏 baiyufeisteam@163.com
 * @LastEditTime: 2023-06-02 16:34:50
 * @FilePath: \homework1\koaserver\app.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require('koa2-cors')
const compress = require('koa-compress')
// const path = require('path')
const static = require('koa-static')
const multer = require('koa-multer')

const svgCaptcha = require('svg-captcha')
const Koa_Session = require('koa-session');
const session_signed_key = ['some secret hurr']
const sessionConfig = require('./session')
const Router = require('koa-router')

const index = require('./routes/index')
const users = require('./routes/users')
const collection = require('./routes/collection')
const order = require('./routes/order')
const news = require('./routes/news')
const wenews = require('./routes/wenews')
const newsimg = require('./routes/newsImg')
const newscomment = require('./routes/newsComment')
const newsCommentImg = require('./routes/newsCommentImg')
const tags = require('./routes/tags')
const background = require('./routes/background')
const buy = require('./routes/buy')
const crop = require('./routes/crop')
const userreceive = require('./routes/userreceive')
const sign = require('./routes/sign')
const flowerpot = require('./routes/flowerpot')
const growtime = require('./routes/growtime')
const administrator = require('./routes/administrator')
const recordlist = require('./routes/recordlist')
const goodscomment = require('./routes/goodscomment')
const coin = require('./routes/coin')
const addtips = require('./routes/addtips')
const guide = require('./routes/guide')
const growtip = require('./routes/growtip')
const plantswiper = require('./routes/plantswiper')

//const formidable = require('koa-formidable'); // 图片处理
const fs = require('fs'); // 图片路径
const path = require('path'); // 图片路径
const serve = require('koa-static');

const formidable = require('formidable')
const mysql = require("mysql");
// const { ctx.db.EXCUTE } = require('./backend/db');
const db = require('./backend/db');


app.use(async (ctx, next) => {
  ctx.db = db;
  await next();
})

// const svg = require('./routes/svg')
const router = require('koa-router')()

const jwt = require('jsonwebtoken');
const mykey = "zara";


// error handler
onerror(app)
// const router = new Router();



// const session = Koa_Session(sessionConfig, app)
// app.keys = session_signed_key;
// app.use(session);
const session = require('koa-session');
app.keys = ['some secret hurr'];

const CONFIG = {
  key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  secure: false, /** (boolean) secure cookie*/
  sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};

app.use(session(CONFIG, app));
// middlewares

// app.use(cors({
//   credentials: true,//默认情况下，Cookie不包括在CORS请求之中。设为true，即表示服务器许可Cookie可以包含在请求中
//   origin: ctx => ctx.header.origin,// web前端服务器地址，注意这里不能用*
// }));

app.use(static(
  path.join(__dirname, "./")
))

// 通过配置multer的dest属性， 将文件储存在项目下的tmp文件中
app.use(multer({ dest: './images/' }).any())

app.use(bodyparser({
  enableTypes: ['json', 'form', 'text'],
  limit: '50000kb',
  textLimit: '20mb',
  formLimit: '20mb',
  jsonLimit: '20mb',
}))

app.use(compress({
  filter(content_type) {
    return /text/i.test(content_type)
  },
  threshold: 2048,
  gzip: {
    flush: require('zlib').constants.Z_SYNC_FLUSH
  },
  deflate: {
    flush: require('zlib').constants.Z_SYNC_FLUSH,
  },
  br: false // disable brotli
}))
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
// app.use(cors())
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'  //pug
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

//cors
app.use(cors({
  origin: 'http://localhost:8081',
  maxAge: 10,
  credentials: true,
  methods: ['GET', 'POST', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));

app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', 'http://localhost:8081');
  ctx.set('Access-Control-Allow-Headers', 'Content-Type');
  ctx.set('Access-Control-Allow-Methods', '*');
  await next();
});


app.use(router.routes());

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(news.routes(), news.allowedMethods())
app.use(collection.routes(), collection.allowedMethods())
app.use(order.routes(), order.allowedMethods())
app.use(news.routes(), news.allowedMethods())
app.use(newsimg.routes(), newsimg.allowedMethods())
app.use(newscomment.routes(), newscomment.allowedMethods())
app.use(newsCommentImg.routes(), newsCommentImg.allowedMethods())
app.use(tags.routes(), tags.allowedMethods())
app.use(background.routes(), background.allowedMethods())
app.use(buy.routes(), buy.allowedMethods())
app.use(crop.routes(), crop.allowedMethods())
app.use(userreceive.routes(), userreceive.allowedMethods())
app.use(sign.routes(), sign.allowedMethods())
app.use(administrator.routes(), administrator.allowedMethods())
app.use(flowerpot.routes(), flowerpot.allowedMethods())
app.use(growtime.routes(), growtime.allowedMethods())
app.use(recordlist.routes(), recordlist.allowedMethods())
app.use(goodscomment.routes(), goodscomment.allowedMethods())
app.use(coin.routes(), coin.allowedMethods())
app.use(addtips.routes(), addtips.allowedMethods())
app.use(guide.routes(), guide.allowedMethods())
app.use(growtip.routes(), growtip.allowedMethods())
app.use(plantswiper.routes(), plantswiper.allowedMethods())

// app.use(svg.routes(), svg.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

// router.get('/code', async (ctx) => {

//   const cap = svgCaptcha.create({
//     size: 4, // 验证码长度
//     width: 160,
//     height: 60,
//     fontSize: 50,
//     ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
//     noise: 2, // 干扰线条的数量
//     color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
//     background: '#eee' // 验证码图片背景颜色
//   })

//   let img = cap.data // 验证码
//   let text = cap.text.toLowerCase() // 验证码字符，忽略大小写

//   ctx.cookies.set(
//     'test', text, {
//     secure: false,
//     httpOnly: false,     //true，客户端不可读取
//     overwrite: true
//   }
//   )

//   // ctx.session.cap = cap.text.toLowerCase();
//   // console.log(ctx.session.cap);

//   // 设置响应头
//   ctx.response.type = 'image/svg+xml';
//   ctx.body = img;
// });


// router.post('/login', async (ctx, next) => {
//   console.log(ctx.request.body);

//   let body = ctx.request.body;
//   let username = body.username;
//   let pwd = body.password;

//   // //把用户信息存到数据库
//   // //let sql = 'insert into user VALUES (' + '"' + username + '"' + ',' + '"' + pwd + '"' +  ')';
//   // ctx.db.EXCUTE('insert into user VALUES (' + '"' + username + '"' + ',' + '"' + pwd + '"' + ')');

//   if (username == "zhangsan" && pwd == "1234") {
//     let token = jwt.sign({ username: "zhangsan" }, mykey);
//     console.log(token);
//     //将token返回到客户端
//     ctx.body = token;
//   }
// })

// router.post("/getdata", async (ctx, next) => {
//   console.log(ctx.req.headers);
//   console.log(ctx.request.body);

//   // let body = JSON.parse(ctx.request.body);
//   // let tokenSaved = body.token;

//   let tokenSaved = JSON.parse(ctx.request.body.token).token;
//   console.log("tokenSaved", +tokenSaved)

//   let token = ctx.req.headers.authorization;
//   let result = jwt.verify(token, mykey);



//   if (tokenSaved == token) {
//     ctx.body = result;
//   }
//   console.log("result:", result);
// })








//tags
//页面初始化时获取数据库内的数据条目
router.post('/gettags', async (ctx, next) => {
  let result = await ctx.db.EXCUTE('SELECT * FROM tags ORDER BY cropid');
  ctx.body = result;
})

//删除tags表item
router.post('/deltags', async (ctx, next) => {
  let id = ctx.request.body.cropid;

  //在数据库中删除对应数据
  await ctx.db.EXCUTE(`DELETE FROM tags WHERE cropid=${id}`)
  //WHERE的筛选条件必须是主键

  //获取删除后的全部数据
  let result = await ctx.db.EXCUTE('SELECT * FROM tags ORDER BY cropid');
  ctx.body = result;
})




app.listen(8080, () => {
  console.log('This server is running at http://localhost:' + 8080)
})

module.exports = app
